package com.cy.store.service.impl;

import com.cy.store.entity.User;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.UserService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

/**
 * @Service注解：将当前类的对象交给Spring来管理，自动创建对象以及对象的维护
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void reg(User user) {

        String username = user.getUsername();
        //查看是否被注册过
        User result = userMapper.findByUsername(username);
        if(result!=null){
            //抛出异常
            throw new UsernameDuplicatedException("用户名被占用");
        }

        //密码加密处理的实现：md5
        // 串 + password + 串 ------md5算法加密，连续加载三次
        // 串就是盐值，一个随机的字符串
        String oldPassword = user.getPassword();
        // 获取盐值
        String salt = UUID.randomUUID().toString().toUpperCase();
        // 将密码和盐值作为整体，进行加密处理，可以忽略原密码强度，提升了数据安全性
        String md5Password = getMD5Password(oldPassword,salt);
        // 将加密之后的密码补全，重新设置到user对象中
        user.setPassword(md5Password);

        /* 补全数据：
            1 is_delete
            2 四个日志信息
            3 盐值
         */
        user.setIsDelete(0);
        user.setCreatedUser(username);
        user.setModifiedUser(username);
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);
        user.setSalt(salt);

        //进行注册
        Integer rows = userMapper.insert(user);
        if(rows != 1){
            throw new InsertException("用户注册过程中产生了未知异常");
        }
    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if(user == null){
            throw new UserNotFoundException("未找到用户");
        }else {
            String pwd = user.getPassword();
            String salt = user.getSalt();
//            System.out.println("pwd="+pwd);
            String md5Password = getMD5Password(password,salt);
//            System.out.println("md5Password = "+md5Password);
            if(!pwd.equals(md5Password)){
                throw new PasswordNotMatchException("密码错误");
            }
        }
        if(user.getIsDelete()==1) throw new UserNotFoundException("用户已注销");
        //只用三个属性，数据越少，速度越快
        return new User(user.getUid(),user.getUsername(),user.getAvatar());
    }

    /**
     * 更新密码
     * @param uid
     * @param username
     * @param oldPassword
     * @param newPassword
     */
    @Override
    public void changePassword(int uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.findByUid(uid);
        if(result==null || result.getIsDelete()==1){
            throw new UserNotFoundException("未找到用户");
        }
        // 看原始密码是否正确
        String oldMD5Password = getMD5Password(oldPassword, result.getSalt());
        if(!oldMD5Password.equals(result.getPassword())){
            throw new PasswordNotMatchException("原密码错误");
        }
        // 更新密码
        String newMD5Password = getMD5Password(newPassword, result.getSalt());
        Date date = new Date();
        int row = userMapper.updatePasswordByUid(uid,newMD5Password,username,date);
        if(row!=1){
            throw new UpdateException("更改密码时出现异常");
        }
    }

    @Override
    public User findByUid(int uid) {
        User user = userMapper.findByUid(uid);
        if(user==null || user.getIsDelete()==1){
            throw new UserNotFoundException("用户未找到");
        }
        User u = new User();
        u.setPhone(user.getPhone());
        u.setEmail(user.getEmail());
        u.setGender(user.getGender());

        return user;
    }

    @Override
    public void changeInfo(int uid,String username,User user){
        User result = userMapper.findByUid(uid);
        if(result==null || result.getIsDelete()==1){
            throw new UserNotFoundException("用户未找到");
        }
        user.setUid(uid);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());
        Integer rows = userMapper.updateInfoByUid(user);
        if(rows != 1){
            throw new UpdateException("修改信息时出错");
        }
    }

    @Override
    public void changeAvatar(int uid, String username, String avatar) {
        User user = findByUid(uid);
        user.setAvatar(avatar);
        user.setModifiedTime(new Date());
        user.setModifiedUser(username);
        userMapper.updateAvatarByUid(user);
    }

    /**
     * 定义MD5算法加密
     * */
    private  String getMD5Password(String password,String salt){

        //md5加密方法的调用(三次)
        for(int i=0;i<3;i++){
            password = DigestUtils.md5DigestAsHex((salt+password+salt).getBytes()).toUpperCase();
        }
        // 返回加密之后的密码
        return password;
    }

}
